package com.yinhanshi.s3test.utils;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.ProgressEvent;
import com.yinhanshi.s3test.MainActivity;
import com.yinhanshi.s3test.R;
import com.yinhanshi.s3test.downlaod.Downloader;
import com.yinhanshi.s3test.upload.UploadIterruptedException;
import com.yinhanshi.s3test.upload.Uploader;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DownloadService extends IntentService {

    public static final String ARG_FILE_PATH = "download_file_path";
    public static final String DOWNLOAD_STATE_CHANGED_ACTION = "com.readystatesoftware.simpl3r.example.DOWNLOAD_STATE_CHANGED_ACTION";
    public static final String DOWNLOAD_CANCELLED_ACTION = "com.readystatesoftware.simpl3r.example.DOWNLOAD_CANCELLED_ACTION";
    public static final String S3KEY_EXTRA = "s3key";
    public static final String PERCENT_EXTRA = "download_percent";
    public static final String MSG_EXTRA = "download_msg";

    private static final int NOTIFY_ID_UPLOAD = 1347;

    private AmazonS3Client s3Client;
    private Downloader downloader;

    private NotificationManager nm;

    public DownloadService() {
        super("simpl3r-example-download");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //设置连接时的参数
        ClientConfiguration config = new ClientConfiguration();
        //设置连接方式为HTTP，可选参数为HTTP和HTTPS
        config.setProtocol(Protocol.HTTP);
        //设置网络访问超时时间
        config.setConnectionTimeout(50000);
        //获得S3对象
        s3Client = new AmazonS3Client(
                new BasicAWSCredentials(getString(R.string.s3_access_key), getString(R.string.s3_secret)), config);
        //设置point
        s3Client.setEndpoint(getString(R.string.s3_end_point));

        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        IntentFilter f = new IntentFilter();
        f.addAction(DOWNLOAD_CANCELLED_ACTION);
        registerReceiver(downloadCancelReceiver, f);
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        String s3BucketName = getString(R.string.s3_bucket);
        // 文件的存储路径
        String filePath = "/storage/emulated/0/hulu/downloads/999.mp4";
        File fileToDownload = new File(filePath);
        // 获得文件在S3中key
        final String s3ObjectKey = intent.getStringExtra(ARG_FILE_PATH);
        final String msg = "Downloading " + s3ObjectKey + "...";
        // 要下载的文件总长度
        long fileTotalLength = 30565774;
        getFileLength(s3ObjectKey);
        // 创建 Downloader
        downloader = new Downloader(this, s3Client, s3BucketName, s3ObjectKey, fileToDownload, fileTotalLength);
        // 进度监听
        downloader.setProgressListener(new Downloader.DownloadProgressListener() {
            @Override
            public void progressChanged(long bytesUploaded, int percentUploaded) {
                Notification notification = buildNotification(msg, percentUploaded);
                nm.notify(NOTIFY_ID_UPLOAD, notification);
                broadcastState(s3ObjectKey, percentUploaded, msg);
            }
        });
        // 通知上传开始
        Notification notification = buildNotification(msg, 0);
        nm.notify(NOTIFY_ID_UPLOAD, notification);
        broadcastState(s3ObjectKey, 0, msg);
        // 开始上传
        try {
            downloader.start();
            broadcastState(s3ObjectKey, -1, "File successfully download");
        } catch (UploadIterruptedException uie) {
            broadcastState(s3ObjectKey, -1, "User interrupted");
        } catch (Exception e) {
            e.printStackTrace();
            broadcastState(s3ObjectKey, -1, "Error: " + e.getMessage());
        }
    }

	/**
	 * 获取指定key文件的信息
	 * @param s3ObjectKey
	 */
    public void getFileLength(String s3ObjectKey) {
        ObjectMetadata ob = s3Client.getObjectMetadata(getString(R.string.s3_bucket), s3ObjectKey);
        Log.e("TAG", "getFileLength: " + ob.getContentLength());
    }

    @Override
    public void onDestroy() {
        nm.cancel(NOTIFY_ID_UPLOAD);
        unregisterReceiver(downloadCancelReceiver);
        super.onDestroy();
    }

    private void broadcastState(String s3key, int percent, String msg) {
        Intent intent = new Intent(DOWNLOAD_STATE_CHANGED_ACTION);
        Bundle b = new Bundle();
        b.putString(S3KEY_EXTRA, s3key);
        b.putInt(PERCENT_EXTRA, percent);
        b.putString(MSG_EXTRA, msg);
        intent.putExtras(b);
        sendBroadcast(intent);
    }

    private Notification buildNotification(String msg, int progress) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setWhen(System.currentTimeMillis());
        builder.setTicker(msg);
        builder.setContentTitle(getString(R.string.app_name));
        builder.setContentText(msg);
        builder.setSmallIcon(R.drawable.ic_stat_uploading);
        builder.setOngoing(true);
        builder.setProgress(100, progress, false);

        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        builder.setContentIntent(contentIntent);

        return builder.build();
    }

    private BroadcastReceiver downloadCancelReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (downloader != null) {
                downloader.interrupt();
            }
        }
    };

}
